/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatsoft.server.buz;

import ChatSoft.model.buz.SendObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 *
 * @author VinhThien
 */
public class FileController extends Thread {

    public String navigate;
    public InputStream inStream;
    public Object recieveObject = null;
    SendObject sendObject;
    private String UserName;
    private Socket socke;

    public FileController(InputStream input, String navi, Socket sock) {
        inStream = input;
        navigate = navi;
        socke = sock;
    }

    @Override
    public void run() {
        byte tempBuffer[] = new byte[10000];
        while (true) {
            try {

                OutputStream outStream = ServerStaticVariable.fileOnlineStream.get(navigate);
                if (outStream != null) {

                    int filesize = 6022386;
                    int bytesRead;
                    int current = 0;

                    // receive file 
                    byte[] mybytearray = new byte[filesize];
                    InputStream is = inStream;
                    bytesRead = is.read(mybytearray, 0, mybytearray.length);
                    current = bytesRead;

                    do {
                        bytesRead =
                                is.read(mybytearray, current, (mybytearray.length - current));
                        if (bytesRead >= 0) {
                            current += bytesRead;
                        }
                    } while (bytesRead > -1);

                    // sendfile 
                    OutputStream os = outStream; 
                    os.write(mybytearray,0,current); 
                    os.flush(); 
                    ServerStaticVariable.socketFileOnlineStream.get(navigate).close();
                    socke.close();
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
